package com.pengcheng.taskapplication.mvp.view.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.pengcheng.taskapplication.R;
import com.pengcheng.taskapplication.util.SPUtils;
import com.pengcheng.taskapplication.util.ToastUtils;

import butterknife.BindView;
import butterknife.OnClick;


public class Html5AgressActivity extends BaseActivity {

    private String mUrl;

    private LinearLayout mLayout;
    private WebView mWebView;
    @BindView(R.id.checkbox)
    CheckBox checkBox;
    @BindView(R.id.ll_commit)
    LinearLayout linearLayout;
    @BindView(R.id.tv_center_title)
    TextView tv_center_title;

    private boolean flag;


//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_web_layout);
//
//        mUrl = getIntent().getStringExtra("url");
//        Log.d("Url:", mUrl);
//
//        mLayout = (LinearLayout) findViewById(R.id.web_layout);
//
//        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//        mWebView = new WebView(getApplicationContext());
//        mWebView.setLayoutParams(params);
//        mLayout.addView(mWebView);
//
//        WebSettings mWebSettings = mWebView.getSettings();
//        mWebSettings.setSupportZoom(true);
//        mWebSettings.setLoadWithOverviewMode(true);
//        mWebSettings.setUseWideViewPort(true);
//        mWebSettings.setDefaultTextEncodingName("utf-8");
//        mWebSettings.setLoadsImagesAutomatically(true);
//
//        //调用JS方法.安卓版本大于17,加上注解 @JavascriptInterface
//        mWebSettings.setJavaScriptEnabled(true);
//
//        saveData(mWebSettings);
//
//        newWin(mWebSettings);
//
//        mWebView.setWebChromeClient(webChromeClient);
//        mWebView.setWebViewClient(webViewClient);
//        mWebView.loadUrl("file:///android_asset/instructions.html");
//    }

    @Override
    protected int layoutResID() {
        return R.layout.activity_web_agress_layout;
    }

    @Override
    protected void initData() {
        mUrl = getIntent().getStringExtra("url");
        Log.d("Url:", mUrl);
        String title =getIntent().getStringExtra("title");
        mLayout = (LinearLayout) findViewById(R.id.web_layout);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mWebView = new WebView(getApplicationContext());
        mWebView.setLayoutParams(params);
        mLayout.addView(mWebView);
        tv_center_title.setText(title);

        WebSettings mWebSettings = mWebView.getSettings();
        mWebSettings.setSupportZoom(true);
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setDefaultTextEncodingName("utf-8");
        mWebSettings.setLoadsImagesAutomatically(true);

        //调用JS方法.安卓版本大于17,加上注解 @JavascriptInterface
        mWebSettings.setJavaScriptEnabled(true);

        saveData(mWebSettings);

        newWin(mWebSettings);

        mWebView.setWebChromeClient(webChromeClient);
        mWebView.setWebViewClient(webViewClient);
        mWebView.loadUrl(mUrl);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                switch (compoundButton.getId()){
                    case R.id.checkbox:
                        if(b){
                           flag=true;
                            linearLayout.setBackgroundResource(R.drawable.bg_apply);
                        }else{
                           flag=false;
                            linearLayout.setBackgroundResource(R.drawable.bg_no_apply);
                        }
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        mWebView.onPause();
        mWebView.pauseTimers(); //小心这个！！！暂停整个 WebView 所有布局、解析、JS。
    }

    @Override
    public void onResume() {
        super.onResume();
        mWebView.onResume();
        mWebView.resumeTimers();
    }

    /**
     * 多窗口的问题
     */
    private void newWin(WebSettings mWebSettings) {
        //html中的_bank标签就是新建窗口打开，有时会打不开，需要加以下
        //然后 复写 WebChromeClient的onCreateWindow方法
        mWebSettings.setSupportMultipleWindows(false);
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    }

    /**
     * HTML5数据存储
     */
    private void saveData(WebSettings mWebSettings) {
        //有时候网页需要自己保存一些关键数据,Android WebView 需要自己设置
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setDatabaseEnabled(true);
        mWebSettings.setAppCacheEnabled(true);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        mWebSettings.setAppCachePath(appCachePath);
    }

    WebViewClient webViewClient = new WebViewClient(){

        /**
         * 多页面在同一个WebView中打开，就是不新建activity或者调用系统浏览器打开
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

    };

    WebChromeClient webChromeClient = new WebChromeClient() {

        //=========HTML5定位==========================================================
        //需要先加入权限
        //<uses-permission android:name="android.permission.INTERNET"/>
        //<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
        //<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            super.onReceivedIcon(view, icon);
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            super.onGeolocationPermissionsHidePrompt();
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);//注意个函数，第二个参数就是是否同意定位权限，第三个是是否希望内核记住
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }
        //=========HTML5定位==========================================================

        //=========多窗口的问题==========================================================
        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(view);
            resultMsg.sendToTarget();
            return true;
        }
        //=========多窗口的问题==========================================================
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mWebView != null) {
            mWebView.clearHistory();
            ((ViewGroup) mWebView.getParent()).removeView(mWebView);
            mWebView.loadUrl("about:blank");
            mWebView.stopLoading();
            mWebView.setWebChromeClient(null);
            mWebView.setWebViewClient(null);
            mWebView.destroy();
            mWebView = null;
        }
    }
    @OnClick({R.id.img_back,R.id.tv_apply,R.id.tv_xieyi})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.tv_xieyi:
                intent =new Intent(context,Html5Activity.class);
                intent.putExtra("url","file:///android_asset/car.html");
                intent.putExtra("title","汽车电子标识申领用户协议");
                startActivity(intent);
                break;
            case R.id.tv_apply:
                if(!flag){
                    ToastUtils.showShortToast("请勾选《汽车电子标识申领用户协议》");
                    return;
                }
                intent =new Intent(context,ApplyActivity.class);
                startActivity(intent);
                Html5AgressActivity.this.finish();
                break;
        }
    }

}